import cv2 #主要用到的python的opencv中的cv2图像处理库
import numpy as np
import face_recognition

# 加载图片
imgElon = face_recognition.load_image_file('ImagesBasic/guo zihan.jpg')
imgElon = cv2.cvtColor(imgElon, cv2.COLOR_BGR2RGB)
imgTest = face_recognition.load_image_file('ImagesBasic/han xian.jpg')
imgTest = cv2.cvtColor(imgTest, cv2.COLOR_BGR2RGB)

# 获取图像尺寸
print(f"Elon Image Shape: {imgElon.shape}")
print(f"Test Image Shape: {imgTest.shape}")

# 定位人脸位置
faceLoc = face_recognition.face_locations(imgElon)[0]
encodeElon = face_recognition.face_encodings(imgElon)[0]
cv2.rectangle(imgElon, (faceLoc[3], faceLoc[0]), (faceLoc[1], faceLoc[2]), (255, 0, 255), 2)

faceLocTest = face_recognition.face_locations(imgTest)[0]
encodeTest = face_recognition.face_encodings(imgTest)[0]
cv2.rectangle(imgTest, (faceLocTest[3], faceLocTest[0]), (faceLocTest[1], faceLocTest[2]), (255, 0, 255), 2)

# 比较人脸
result = face_recognition.compare_faces([encodeElon], encodeTest)
faceDis = face_recognition.face_distance([encodeElon], encodeTest)
print(result, faceDis)
cv2.putText(imgTest, f'{result}{round(faceDis[0], 2)}', (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2)

# 调整图像大小适配显示窗口
# 这里的大小可以根据你显示器的分辨率灵活调整
resize_width = 800
resize_height = 600
imgElon_resized = cv2.resize(imgElon, (resize_width, resize_height))  
imgTest_resized = cv2.resize(imgTest, (resize_width, resize_height))

# 显示图片
cv2.namedWindow('zihan guo', cv2.WINDOW_NORMAL)
cv2.resizeWindow('zihan guo', resize_width, resize_height)
cv2.imshow('zihan guo', imgElon_resized)

cv2.namedWindow('shijie yu', cv2.WINDOW_NORMAL)
cv2.resizeWindow('shijie yu', resize_width, resize_height)
cv2.imshow('shijie yu', imgTest_resized)

# 按ESC键退出
key = cv2.waitKey(0)
if key == 27:
    cv2.destroyAllWindows()
